package com.example.timewidget

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.util.Log
import com.example.timewidget.util.MessegeHelper
import com.example.timewidget.util.MessegeHelper.Companion.MSG_CLIENT
import com.example.timewidget.util.MessegeHelper.Companion.MSG_SERVER

class TimeService : Service() {
    private val TAG = this::class.java.simpleName

    @SuppressLint("HandlerLeak")
    val mMessenger = Messenger(object : Handler() {
        override fun handleMessage(msg: Message) {
            Log.d(TAG, "handleMessage: bbbbbasd")
            if (msg.arg1 == MSG_CLIENT) {
                Log.d(TAG, "handleMessage: bbbbbasd")
                var data = msg.data ?: return
                val content = data.getString(MSG_CLIENT.toString()) ?: return
                Log.d(TAG, "Message from client: $content")

                // 回复消息给客户端
                val replyMsg = Message.obtain()
                replyMsg.arg1 = MSG_SERVER
                val bundle = Bundle()
                bundle.putString(MSG_SERVER.toString(), "听到你的消息了")
                replyMsg.data = bundle

                try {
                    msg.replyTo?.send(replyMsg) // 回信
                } catch (e: RemoteException) {
                    e.printStackTrace()
                }
            }
        }
    })

    override fun onBind(intent: Intent): IBinder {
        return mMessenger.binder
    }
}